import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../constants/app_colors.dart';
import '../models/psychological_test.dart';
import '../models/database_helper.dart';
import 'test_report_screen.dart';

class TestQuestionScreen extends StatefulWidget {
  final TestType testType;

  const TestQuestionScreen({
    Key? key,
    required this.testType,
  }) : super(key: key);

  @override
  State<TestQuestionScreen> createState() => _TestQuestionScreenState();
}

class _TestQuestionScreenState extends State<TestQuestionScreen> {
  late List<TestQuestion> questions;
  late List<int?> answers;
  int currentQuestionIndex = 0;
  bool isLoading = false;

  @override
  void initState() {
    super.initState();
    _initQuestions();
  }

  void _initQuestions() {
    switch (widget.testType) {
      case TestType.SDS:
        questions = SDSTest.questions;
        break;
      case TestType.SAS:
        questions = SASTest.questions;
        break;
      case TestType.SCL90:
        questions = SCL90Test.questions;
        break;
    }
    answers = List.filled(questions.length, null);
  }

  String _getTestTitle() {
    switch (widget.testType) {
      case TestType.SDS:
        return '抑郁自评量表(SDS)';
      case TestType.SAS:
        return '焦虑自评量表(SAS)';
      case TestType.SCL90:
        return '症状自评量表(SCL-90)';
    }
  }

  void _nextQuestion() {
    if (currentQuestionIndex < questions.length - 1) {
      setState(() {
        currentQuestionIndex++;
      });
    } else {
      _submitTest();
    }
  }

  Future<void> _submitTest() async {
    if (answers.contains(null)) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请完成所有题目后再提交')),
      );
      return;
    }

    setState(() => isLoading = true);

    try {
      final nonNullAnswers = answers.map((e) => e!).toList();
      late TestRecord record;

      switch (widget.testType) {
        case TestType.SDS:
          final standardScore = SDSTest.calculateStandardScore(nonNullAnswers);
          final conclusion = SDSTest.getConclusion(standardScore);
          record = TestRecord(
            testType: widget.testType,
            testDate: DateTime.now(),
            answers: nonNullAnswers,
            rawScore: standardScore / 1.25,
            standardScore: standardScore,
            conclusion: conclusion,
            suggestion: SDSTest.getSuggestion(conclusion),
          );
          break;
        case TestType.SAS:
          final standardScore = SASTest.calculateStandardScore(nonNullAnswers);
          final conclusion = SASTest.getConclusion(standardScore);
          record = TestRecord(
            testType: widget.testType,
            testDate: DateTime.now(),
            answers: nonNullAnswers,
            rawScore: standardScore / 1.25,
            standardScore: standardScore,
            conclusion: conclusion,
            suggestion: SASTest.getSuggestion(conclusion),
          );
          break;
        case TestType.SCL90:
          final factorScores = SCL90Test.calculateFactorScores(nonNullAnswers);
          final conclusion = SCL90Test.getConclusion(factorScores);
          record = TestRecord(
            testType: widget.testType,
            testDate: DateTime.now(),
            answers: nonNullAnswers,
            rawScore: factorScores.values.reduce((a, b) => a + b) / factorScores.length,
            standardScore: factorScores.values.reduce((a, b) => a + b) / factorScores.length,
            conclusion: conclusion,
            suggestion: SCL90Test.getSuggestion(factorScores),
          );
          break;
      }

      await DatabaseHelper.instance.insertTestRecord(record);

      if (mounted) {
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => TestReportScreen(record: record),
          ),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('提交失败，请重试')),
      );
    } finally {
      if (mounted) {
        setState(() => isLoading = false);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.pop(context),
        ),
        title: Text(
          _getTestTitle(),
          style: GoogleFonts.zcoolKuaiLe(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: Colors.black,
          ),
        ),
        centerTitle: true,
      ),
      body: Column(
        children: [
          // 进度条和题目序号
          Padding(
            padding: const EdgeInsets.fromLTRB(20, 10, 20, 0),
            child: Column(
              children: [
                // 题目序号和总数
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Text(
                      '${currentQuestionIndex + 1}/${questions.length}',
                      style: GoogleFonts.zcoolKuaiLe(
                        fontSize: 18,
                        color: Colors.black54,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                // 进度条
                ClipRRect(
                  borderRadius: BorderRadius.circular(6),
                  child: Stack(
                    children: [
                      Container(
                        width: double.infinity,
                        height: 12,
                        decoration: BoxDecoration(
                          color: Colors.grey[100],
                          border: Border.all(
                            color: Colors.grey[300]!,
                            width: 1,
                          ),
                          borderRadius: BorderRadius.circular(6),
                        ),
                      ),
                      FractionallySizedBox(
                        widthFactor: (currentQuestionIndex + 1) / questions.length,
                        child: Container(
                          height: 12,
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                              colors: [Colors.blue[400]!, Colors.blue[600]!],
                              begin: Alignment.centerLeft,
                              end: Alignment.centerRight,
                            ),
                            borderRadius: BorderRadius.circular(6),
                            boxShadow: [
                              BoxShadow(
                                color: Colors.blue.withOpacity(0.3),
                                blurRadius: 4,
                                offset: const Offset(0, 2),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),

          // 题目内容区域
          Expanded(
            child: SingleChildScrollView(
              child: Padding(
                padding: const EdgeInsets.fromLTRB(20, 10, 20, 20),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const SizedBox(height: 16),
                    
                    // 题目内容
                    Text(
                      questions[currentQuestionIndex].content,
                      style: GoogleFonts.zcoolKuaiLe(
                        fontSize: 22,
                        fontWeight: FontWeight.w500,
                        color: Colors.black,
                        height: 1.5,
                      ),
                    ),
                    const SizedBox(height: 32),
                    
                    // 选项列表
                    ...List.generate(
                      questions[currentQuestionIndex].options.length,
                      (index) => Padding(
                        padding: const EdgeInsets.only(bottom: 16),
                        child: InkWell(
                          onTap: () {
                            setState(() {
                              answers[currentQuestionIndex] = index;
                            });
                          },
                          child: Container(
                            width: double.infinity,
                            padding: const EdgeInsets.symmetric(
                              horizontal: 20,
                              vertical: 16,
                            ),
                            decoration: BoxDecoration(
                              color: answers[currentQuestionIndex] == index
                                  ? Colors.blue.withOpacity(0.1)
                                  : Colors.white,
                              borderRadius: BorderRadius.circular(8),
                              border: Border.all(
                                color: answers[currentQuestionIndex] == index
                                    ? Colors.blue
                                    : Colors.grey.shade300,
                                width: 1,
                              ),
                            ),
                            child: Row(
                              children: [
                                Container(
                                  width: 24,
                                  height: 24,
                                  decoration: BoxDecoration(
                                    shape: BoxShape.circle,
                                    border: Border.all(
                                      color: answers[currentQuestionIndex] == index
                                          ? Colors.blue
                                          : Colors.grey.shade400,
                                      width: 2,
                                    ),
                                  ),
                                  child: answers[currentQuestionIndex] == index
                                      ? const Center(
                                          child: Icon(
                                            Icons.circle,
                                            size: 14,
                                            color: Colors.blue,
                                          ),
                                        )
                                      : null,
                                ),
                                const SizedBox(width: 12),
                                Expanded(
                                  child: Text(
                                    questions[currentQuestionIndex].options[index],
                                    style: GoogleFonts.zcoolKuaiLe(
                                      fontSize: 20,
                                      color: Colors.black87,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                    
                    // 下一题按钮
                    const SizedBox(height: 40),
                    Container(
                      decoration: BoxDecoration(
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.1),
                            blurRadius: 10,
                            offset: const Offset(0, 2),
                          ),
                        ],
                      ),
                      child: SizedBox(
                        width: double.infinity,
                        height: 50,
                        child: ElevatedButton(
                          onPressed: answers[currentQuestionIndex] == null
                              ? null
                              : _nextQuestion,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue,
                            foregroundColor: Colors.white,
                            disabledBackgroundColor: Colors.grey[300],
                            disabledForegroundColor: Colors.grey[500],
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(25),
                            ),
                            elevation: 0,
                          ),
                          child: Text(
                            currentQuestionIndex < questions.length - 1 ? '下一题' : '提交',
                            style: GoogleFonts.zcoolKuaiLe(
                              fontSize: 20,
                              color: Colors.white,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
} 